<template>
    <div class="market-view">
        <a-card :title="$t('market')" :bordered="false">
            <p>{{ $t('marketRefresh') }}: {{ formatCountdown(refreshCountdown.value) }}</p>
            <a-tabs default-active-key="buy">
                <a-tab-pane key="buy" :tab="$t('buyCard')">
                    <a-row :gutter="[16, 16]">
                        <a-col v-for="card in buyableCards" :key="card.id">
                            <a-card hoverable class="card-container">
                                <img :src="cardConfig.cards[card.id]?.image || 'https://via.placeholder.com/120x150'"
                                     alt="卡片图片" class="card-image"/>
                                <div class="card-info">
                                    <p class="card-title">{{ cardConfig.cards[card.id]?.name || card.id }}</p>
                                    <p class="card-value">{{ card.value }}</p>
                                </div>
                                <a-button type="primary" size="small" @click="gameStore.buyCard(card.id)"
                                          :disabled="gameStore.playerData.gold < 20">
                                    {{ $t('buy') }} (20 {{ $t('gold') }})
                                </a-button>
                            </a-card>
                        </a-col>
                    </a-row>
                </a-tab-pane>
                <a-tab-pane key="exchange" :tab="$t('exchange')">
                    <a-row :gutter="[16, 16]">
                        <a-col v-for="card in gameStore.marketCards" :key="card.id">
                            <a-card hoverable class="card-container">
                                <img :src="cardConfig.cards[card.id]?.image || 'https://via.placeholder.com/120x150'"
                                     alt="卡片图片" class="card-image"/>
                                <div class="card-info">
                                    <p class="card-title">{{ cardConfig.cards[card.id]?.name || card.id }}</p>
                                    <p class="card-value">{{ card.value }}</p>
                                </div>
                                <a-button size="small" @click="showExchangeModal(card)">{{
                                        $t('exchangeCards')
                                    }}
                                </a-button>
                            </a-card>
                        </a-col>
                    </a-row>
                </a-tab-pane>
            </a-tabs>
        </a-card>
        <a-modal v-model:visible="exchangeModalVisible" :title="$t('exchangeCards')" @ok="handleExchange"
                 :confirm-loading="exchangeLoading">
            <a-row :gutter="[16, 16]">
                <a-col v-for="(cardId, index) in allPlayerCards" :key="index">
                    <div class="card-wrapper"
                         :class="{ 'disabled': exchangeTarget && cardConfig.cards[cardId]?.value !== exchangeTarget.value }">
                        <a-checkbox
                            :value="cardId"
                            v-model:checked="selectedCards[index]"
                            :disabled="exchangeTarget && cardConfig.cards[cardId]?.value !== exchangeTarget.value"
                        >
                            <a-card class="card-container">
                                <img :src="cardConfig.cards[cardId]?.image || 'https://via.placeholder.com/120x150'"
                                     alt="卡片图片" class="card-image"/>
                                <div class="card-info">
                                    <p class="card-title">{{ cardConfig.cards[cardId]?.name || cardId }}</p>
                                    <p class="card-value">{{ cardConfig.cards[cardId]?.value || '未知' }}</p>
                                </div>
                            </a-card>
                        </a-checkbox>
                    </div>
                </a-col>
            </a-row>
        </a-modal>
    </div>
</template>

<script setup>
import {computed, onMounted, onUnmounted, ref} from 'vue'
import {useGameStore} from '../stores/game'
import cardConfig from '../config/cards.json'
import {message} from 'ant-design-vue'
import {useI18n} from 'vue-i18n'

const {t} = useI18n()
const gameStore = useGameStore()
const refreshCountdown = ref(1800)
const exchangeModalVisible = ref(false)
const selectedCards = ref([])
const exchangeTarget = ref(null)
const exchangeLoading = ref(false)
let timer = null

const buyableCards = Object.entries(cardConfig.cards)
    .filter(([_, card]) => card.value === 10)
    .map(([id, card]) => ({id, ...card}))

const allPlayerCards = computed(() => gameStore.playerData.cards)

const formatCountdown = (seconds) => {
    if (!Number.isFinite(seconds) || seconds < 0) return '0s'
    if (seconds < 60) return `${Math.floor(seconds)}s`
    if (seconds < 3600) {
        const minutes = Math.floor(seconds / 60)
        const secs = Math.floor(seconds % 60)
        return `${minutes}m ${secs}s`
    }
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = Math.floor(seconds % 60)
    return `${hours}h ${minutes}m ${secs}s`
}

onMounted(() => {
    gameStore.refreshMarket()
    if (!timer) {
        timer = setInterval(() => {
            refreshCountdown.value = Math.max(0, refreshCountdown.value - 1)
            if (refreshCountdown.value <= 0) {
                gameStore.refreshMarket()
                refreshCountdown.value = 1800
                message.success(t('marketRefreshed'))
            }
        }, 1000)
    }
})

onUnmounted(() => {
    if (timer) {
        clearInterval(timer)
        timer = null
    }
})

const showExchangeModal = (card) => {
    exchangeTarget.value = card
    selectedCards.value = Array(allPlayerCards.value.length).fill(false)
    exchangeModalVisible.value = true
}

const handleExchange = async () => {
    if (!exchangeTarget.value) {
        message.error(t('noExchangeTarget'))
        return
    }
    const cardsToExchange = allPlayerCards.value.filter((_, index) => selectedCards.value[index])
    if (cardsToExchange.length === 0) {
        message.error(t('selectAtLeastOneCard'))
        return
    }
    exchangeLoading.value = true
    try {
        await gameStore.exchangeCard(cardsToExchange, exchangeTarget.value.id)
        exchangeModalVisible.value = false
    } catch (error) {
        message.error(t('exchangeFailed'))
    } finally {
        exchangeLoading.value = false
    }
}
</script>

<style scoped>
.market-view {
    padding: 0;
}

.card-container {
    width: 120px;
    height: 150px;
    padding: 8px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s;
}

.card-container:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-image {
    width: 100%;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
}

.card-info {
    text-align: center;
    margin-top: 4px;
}

.card-title {
    font-size: 12px;
    font-weight: bold;
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.card-value {
    font-size: 10px;
    color: #888;
    margin: 0;
}

.card-wrapper {
    position: relative;
}

.card-wrapper.disabled .card-container {
    opacity: 0.5;
}

.card-wrapper.disabled::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(200, 200, 200, 0.5);
    pointer-events: none;
}
</style>